package main

import (
	"context"
	"p2p-server/pkg/database"
	"p2p-server/pkg/middleware"
	"p2p-server/pkg/room"
	"p2p-server/pkg/server"
	"p2p-server/pkg/util"

	"github.com/gogf/gf/v2/os/gcfg"
)

func main() {
	cfg := gcfg.Instance("configs/config.yaml")
	ctx := context.Background()

	// 初始化数据库连接
	err := database.InitDB()
	if err != nil {
		util.Errorf("初始化数据库失败: %v", err)
		return
	}
	defer database.CloseDB()

	roomManager := room.NewRoomManager()
	wsServer := server.NewP2PServer(roomManager.HandleNewWebSocket)
	
	// 添加鉴权中间件
	wsServer.AddMiddleware(middleware.AuthMiddleware)

	sslCert := cfg.MustGet(ctx, "general.cert", "configs/certs/cert.pem").String()
	sslKey := cfg.MustGet(ctx, "general.key", "configs/certs/key.pem").String()
	bindAddress := cfg.MustGet(ctx, "general.bind", "0.0.0.0").String()
	port := cfg.MustGet(ctx, "general.port", "8000").Int()
	htmlRoot := cfg.MustGet(ctx, "general.html_root", "html").String()

	config := server.DefaultConfig()
	config.Host = bindAddress
	config.Port = port
	config.CertFile = sslCert
	config.KeyFile = sslKey
	config.HTMLRoot = htmlRoot
	wsServer.Bind(config)
}
